<template>
  <div class="custom-tree-container">
    <el-tree
      :data="dataSource"
      node-key="id"
      show-checkbox
      ref="treeFata"
      default-expand-all
      @check-change="checkChange"
      @node-click="nodeClick"
      highlight-current
      :default-checked-keys="findKeysWithDefaultTrue(dataSource)"
     
    >
      <template #default="{ node, data }">
        <span class="custom-tree-node">
          <div class="d-flex">
          
            <div class="ms-3"  :style="{color:node.data.show&&node.data.type!='folder'?'#5CE1FF':'#fff'}" style="font-size: 20px;">{{ node.label }}</div>
              <div v-if="node.data.type=='folder'" style="width: 30px;height: 50px;padding: 10px;">
                <div   style="background-color: #1D3A44;width: 40px;height: 25px;    font-size: 20px; text-align: center;border-radius: 13px;
    line-height: 26px;" >
            {{ calcCheckNum(node) }}
          </div>
              </div>
         
          </div>
           <div  v-if="!node.expanded&&data.children.length>0" style="margin-left: 177px;height: 20px;position: relative;" >
                <img src="../../assets/image/svg/down.png" style="  width: 14px; height: 14px; position: absolute;">
           </div>
           <div  v-if="node.expanded&&data.children.length>0" style="margin-left: 177px;height: 20px;    position: relative;" >
                <img src="../../assets/image/svg/up.png" style="  width: 14px; height: 14px;    position: absolute;">
           </div>
          <!-- <span v-if="node.data.show">
            <a @click="changeshow(node, data)">
              <img src="../../assets/image/svg/eyeOpen.png" class="icon" />
            </a>
          </span> -->
          <div>
            <span v-if="node.data.type!='folder'">
            <a @click="location(node, data)">
              <img src="../../assets/image/svg/location.png" class="icon" />
            </a>
          </span>
          <span v-if="node.data.type!='folder'">
            <a @click="openOpacityControl(node, data, $event)">
              <img src="../../assets/image/svg/alpha.png" class="icon" />
            </a>
          </span>
          </div>
      
        </span>
      </template>
    </el-tree>
  
  </div>
  <div v-show="OpacityControlVisible" class="OpacityControl" id="OpacityControl" >
  <div>透明度设置</div>

  <el-slider
          @input="changeOpacity"
          v-model="sliderValue"
          style="width: 250px"
          :min="0"
          :max="100"
          :step="1"
          :show-tooltip="true"
        >
        </el-slider>
     
</div>
</template>

<script lang="ts" setup>
import {
  defineComponent,
  ref,
  Ref,
  shallowRef,
  computed,
  onMounted,
  watch,
  getCurrentInstance,
} from "vue";
import type Node from "element-plus/es/components/tree/src/model/node";
import { MouseMenuDirective } from "@howdyjs/mouse-menu";
import { includes } from "lodash";
import { ElMessage } from "element-plus";
import { useRoute, useRouter } from "vue-router";
import { useStore } from "vuex";
import { useFunc } from "@/hook/useFunc";
import { use } from "echarts";

const appContext = getCurrentInstance()?.appContext;
const ctx = (appContext as any).config.globalProperties;
const store = useStore();
const viewer = (ctx as any).$viewer;
const utum3d = (ctx as any).$utum3d;
const treeFata = ref(null);
const sliderValue:any = ref(100);
//获取默认展示图层key
const findKeysWithDefaultTrue=(data:any)=>{
 console.log(data,'datas');

  let keys:any = [];

// 定义一个递归函数来遍历所有元素和子元素
function traverse(items:any) {
  items.forEach((item:any) => {
    // 如果 default 为 true，将 key 添加到结果数组中
    if (item.default && item.type != 'folder') {
      console.log(item.label,'label',item.id);
      
      keys.push(item.id);
    }
    // 如果存在 children，递归遍历 children
    if (item.children && item.children.length) {
      traverse(item.children);
    }
  });
}

// 从最顶层的数组开始遍历
traverse(data);
 console.log(keys,'keys');
 
// 返回包含所有符合条件的 key 的数组
return keys;
}
const props = defineProps({
  mapLoaded: {
    type: Boolean,
    default: false,
  },
  activeNav: {
    type: Object,
    default: {},
  },
  title: {
    type: String,
    default: "",
  },
});
// let basemap:any =null
const basemap: any = ref(null);
const dataSource = ref([]);
const calcCheckNum=(node:any)=>{
//  let num= (treeFata as any).value.getCheckedKeys(node.data.id);
//  console.log(num,'num');
let key =node.data.id
const treeInstance =(treeFata as any).value;
  if (!treeInstance) {
    console.error("Tree instance is not available.");
    return;
  }

  const allChecked = treeInstance.getCheckedNodes();
  const targetNode = findNode(treeInstance.store.nodesMap, key);
  if (targetNode) {
    let count = 0;
    function countCheckedNodes(node:any) {
      
      if (node.checked && node.level>1) {
        count++;
      }
      node.childNodes.forEach(countCheckedNodes);
    }
    countCheckedNodes(targetNode);
    console.log(`Total checked nodes under key ${key}: ${count}`);
    return count
  } else {
    console.log('Key not found');
    return 0
  }
  function findNode(nodesMap:any, key:any) {
  return nodesMap[key];
}
} 
watch(props, (props) => {
  let arr = getTreeData();
  dataSource.value = useFunc().getDataTreeDataByTitle(
    props.activeNav.title.toString(),
    arr,
    'change'
  );
});

const vMouseMenu = MouseMenuDirective;
const addOrUpdateAuthorityFileVisible = ref(false);
const correntKey = ref();

interface Tree {
  id: string;
  label: string;
  show: Boolean;
  type: string;
  children?: Tree[];
  options?: Object;
}
const loadedlayer = ref([] as any);
const checkChange = (e: any, check: any) => {
  if(e.type!='folder'){
    useFunc().changeVisible(e,check);
    changeDataByKey(e.id, dataSource.value, check);
  console.log(dataSource.value, "dataSource.value");

  }
  
  // updateChildrenShow(e, check);
};
const updateChildrenShow = (children: any[], show: Boolean) => {
    if (children) {
      children.forEach((child) => {
        console.log(child,show, "child");
        child.data.show = show; // 子节点的显示状态与父节点保持一致
        updateChildrenShow(child.children, show); // 递归更新
      });
    }
  };
// 眼睛定位
const location = (node: any, data: any) => {
   useFunc().locationByid(data.id.toString());
};
// 透明化调整
const position=ref({})
const OpacityControlVisible=ref(false)
const activeNode =ref()
// 打开透明度调节
const openOpacityControl = (node: any, data: any,event:any) => {
  OpacityControlVisible.value=!OpacityControlVisible.value
position.value={ x: event.clientX, y: event.clientY };
const div:any = document.getElementById('OpacityControl');
div.style.top = event.clientY-620 + 'px';
div.style.left = 250 + 'px';
activeNode.value=node
sliderValue.value=useFunc().getUniqueOpacity(node)
};

const changeOpacity=(value:any)=>{
  console.log(value,'value');
  useFunc().changeOpacity(activeNode.value,value)
  
}
const changeshow = (node: any, data: any) => {
  //  console.log(node, data, "node");
   
  // //   递归
  // const updateChildrenShow = (children: any[], show: Boolean) => {
  //   if (children) {
  //     children.forEach((child) => {
  //       console.log(child,show, "child");
  //       child.data.show = show; // 子节点的显示状态与父节点保持一致
  //       useFunc().changeVisible(child.data);
  //       updateChildrenShow(child.children, show); // 递归更新
  //     });
  //   }
  // };
  // if (node.childNodes.length > 0) {
  //   data.show = !data.show;
  //   updateChildrenShow(node.childNodes, data.show);
  // } else {
  //   data.show = !data.show;
  //   useFunc().changeVisible(data);
  // }
};

const changeDataByKey = (key: string, data: any, show: Boolean) => {
  
  if (data.id === key) {
    data.show = show;
  } else if (data.children) {
    data.children.forEach((child: any) => {
      changeDataByKey(key, child, show);
    });
  }
};
const nodeClick = (e: any) => {};
const highlightNode = (node: any) => {
  if (node) {
    node.highlighted = true;
    if (node.children) {
      node.children.forEach((child: any) => {
        highlightNode(child);
      });
    }
  }
};
const ClickAppendData = ref();
const append = (data: Tree) => {
  addOrUpdateAuthorityFileVisible.value = true;
  ClickAppendData.value = data;
};

const layerData = ref();
onBeforeMount(() => {});
onMounted(() => {
  let arr = getTreeData();
  dataSource.value = useFunc().getDataTreeDataByTitle(
    props.activeNav.title.toString(),
    arr,
    'init'
  );
});
//扁平化node节点
const getTreeData = () => {
  const valueFromLocalStorage: any = localStorage.getItem("mapTree");
  let flat = JSON.parse(valueFromLocalStorage);
  if (flat) {
    if (flat._rawValue) {
      return flat._rawValue;
    } else {
      return flat;
    }
  }
};
const options = ref({
  useLongPressInMobile: true,
  menuWrapperCss: {
    background: "#eeeeee",
    boxShadow: "0 0 10px #ccc",
  },
  menuItemCss: {
    arrowSize: "8px",
  },
});
</script>

<style>
.el-checkbox__inner{
  height: 22px !important;
  width: 22px !important;
}
.el-checkbox__inner::after{
  height: 12px !important;
  left: 8px !important ;
}
.el-tree {
  --el-tree-node-hover-bg-color: #30496f; /* 替换 #yourColor 为你想要的颜色值 */
}
.el-dialog {
  background-color: var(--navBArBackGround);
}
.icon {
  width: 28px;
  height: 28px;
}
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
  height: 20px;
}
.el-tree {
  background: transparent !important;
  width: 400px;
  border-radius: 10px;
}
.el-tree-node__label{

}
.custom-tree-node{
  font-size: 22px;
  line-height: 50px;
  font-family: "OPPOSans-Regular";
}
.el-tree-node__content {
  /* background-color: var(--navBArBackGround); */
  /* opacity: 0.8; */
  flex-direction: row-reverse;
  height: 38px;
  color: #fff
}
.el-tree-node__content:hover {
  background-color: var(--navBArHighBackGround);
}
/* //设置选中样式 */
.el-tree-node:focus > .el-tree-node__content {
  background: rgba(11, 28, 35, 0.8)!important;
}
.__menu__wrapper {
  z-index: 99999999;
}
/* el-popper is-pure is-light el-select__popper */
.el-select__popper {
  z-index: 99999999 !important;
}
.el-select-dropdown{
  background-color:#154151;

}
.el-select-dropdown__wrap.el-scrollbar__wrap.el-scrollbar__wrap--hidden-default {
  /* background-color: var(--navBArBackGround); */
}
.el-select-dropdown__item.selected:hover {
  background-color:#37aeda!important

}
.el-select-dropdown__item.hover {
  background-color:#37aeda !important
}
.el-select-dropdown__item.selected {
  background-color:#154151 !important;
  color: #5ce1ff;

}
.el-popper.is-light{
  border: 1px solid #154151!important;
}
.el-select__popper.el-popper[data-popper-placement^=bottom] .el-popper__arrow::before{
  background-color: #154151 !important;
}
.el-select-dropdown__item {
  background-color:#154151!important;
  color: #DAF5FA;
}
.el-popper.is-light .el-popper__arrow::before{
  border: 1px solid #154151!important;
}
/* .el-select-dropdown__item {
  color: var(--dropdownTextColor);
  background-color: var(--navBArBackGround);
} */

/* .el-select-dropdown__item:hover {
  background-color: var(--navBArBackGround);
} */

.el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content {
  background:rgb(45 124 156 / 80%) !important;

  /* color: #dadada; */
}
.el-checkbox__inner {
  width: 25px;
  height: 25px;
}
.el-checkbox__inner::after{
  height: 12px;
    left: 10px;
}
.el-checkbox__input.is-indeterminate .el-checkbox__inner::before{
  top:10px
}
.el-checkbox{
  order: 1;
}
</style>

<style scoped>
.OpacityControl{
  background-color: aliceblue;
  width: 323px;
  height: 100px;
  position: absolute;
  z-index: 999999999;
  background-color: rgba(6, 38, 51, 0.5); /* 半透明背景色 */
  padding: 20px;
  font-size: 20px;
color: #fff;
      backdrop-filter: blur(5px); /* 模糊效果 */
}

</style> 
<style>
.el-tree-node__content>.el-tree-node__expand-icon {
    position: absolute;
    opacity: 0;
  }
 
 .el-tree-node__content {
    position: relative;
  }
</style>
 <!-- <style>
 .el-tree .el-tree-node__expand-icon.expanded
{
    -webkit-transform: rotate(0deg);
    transform: rotate(0deg);
}
 .el-tree .el-icon-caret-right:before
/* 折起的样式 */
{
    /* folderMinus.png 展开的样式图片 */
    background: url("../../assets/image/svg/up.png") no-repeat center ;
    content: '';
    display: block;
    width: 18px;
    height: 18px;
    font-size: 18px;
    background-size: 18px;
}
/* 展开的样式 */
 .el-tree .el-tree-node__expand-icon.expanded.el-icon-caret-right:before
{
   /*folderOpen.png 展开的样式图片 */
    background: url("../../assets/image/svg/down.png")   no-repeat  center;
    content: '';
    display: block;
    width: 18px;
    height: 18px;
    font-size: 18px;
    background-size: 18px;
}
/* 最后一级 */
  .el-tree-node__expand-icon.is-leaf::before
{
    /* file.png 是最后一级图片 */
    background: url("../../assets/image/svg/up.png")   no-repeat  center center;
    content: '';
    display: block;
    width: 18px;
    height: 18px;
    font-size: 18px;
    background-size: 18px;
}
</style> -->
